#include "mainwindow.h"
//#include "ui_mainwindow.h"
#include <QMovie>
#include <QTableView>
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QMediaPlayer>
#include <sys/inotify.h>
#include <unistd.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setFixedSize(480, 360);
    move(0,0);


    Object *obj = new Object;
    obj->start();


}

MainWindow::~MainWindow()
{

}

void MainWindow::paintEvent(QPaintEvent *)
{

}



const char *event_str[12] =
{
    "IN_ACCESS",
    "IN_MODIFY",
    "IN_ATTRIB",
    "IN_CLOSE_WRITE",
    "IN_CLOSE_NOWRITE",
    "IN_OPEN",
    "IN_MOVED_FROM",
    "IN_MOVED_TO",
    "IN_CREATE",
    "IN_DELETE",
    "IN_DELETE_SELF",
    "IN_MOVE_SELF"
};

void Object::run()
{
    int fd = inotify_init();
    if(fd < 0)
    {
        qDebug() << "inotify_init fail";
        return ;
    }

    int wd = inotify_add_watch(fd,"/userdata/usrData",IN_CREATE | IN_DELETE| IN_DELETE_SELF);
    if(wd < 0)
    {
        qDebug() << "inotify_add_watch fail";
        return ;
    }

    char buf[BUFSIZ] = {0};
    int nread = 0;
    struct inotify_event *event;
    while(1)
    {
        int length = read(fd, buf, sizeof(buf) - 1);
        nread = 0;
        while(length > 0)
        {
            //qDebug() << "length = " << length << "  nread = " << nread;
            event = (struct inotify_event *)&buf[nread];
            qDebug() << "event->mask = " << QString::number(event->mask, 2) << " " << event->mask;
            // 遍历所有事件
            for(int i = 0; i< 12; i++)
            {
                // 判断事件是否发生
                if( (event->mask >> i) & 1 )
                {
                    // 该监控项为目录或目录下的文件时
                    if(event->len > 0)
                    {
                        //fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
                        qDebug() << event->name << " " << event_str[i];
                    }
                    // 该监控项为文件时
                    else if(event->len == 0)
                    {
                        if(event->wd == wd)
                        {
                            //fprintf(stdout, "--- %s\n", event_str[i]);
                            qDebug() << event_str[i];
                        }
                    }
                }
            }

            nread = nread + sizeof(struct inotify_event) + event->len;
            length = length - sizeof(struct inotify_event) - event->len;
        }
    }

    close(fd);
}
